<?php

//for print documentation in all rest module unit folder
function printDoc($enable) {
  if ($enable) {
    foreach(glob('module/*/rest/*') as $rest) {
      printf("<h3>$rest</h3>");
      printf('<br><pre>');
      foreach(file("{$rest}") as $line) {
        printf($line);
      }
      printf('</pre><br>');
    }
  }
}

//for easy install migrations mysql
function mysqlModules($db, $enable) {
  //scale all modules hiden mysql scripts
  $remove_php_open_key_tmp = 'sed "s/<?php//g" -i $1';
  $remove_php_open_multiline_comment_tmp = 'sed "s/\/\*//g" -i $1';
  $remove_php_close_multiline_comment_tmp = 'sed "s/\*\///g" -i $1';
  $remove_php_close_key_tmp = 'sed "s/?>//g" -i $1';
  $remove_first_space_tmp = 'sed "1{/^$/d}" -i $1';
  $remove_second_space_tmp = 'sed "1{/^$/d}" -i $1';
  $remove_last_space_tmp = 'sed -z "s/.$//" -i $1';

  $add_php_multiline_comment = 'sed "1s/^/\/\*\n/" -i $1';
  $add_php_open_key_comment = 'sed "1s/^/<?php\n/" -i $1';
  $add_php_close_multiline_comment = 'echo "*/" >> $1';
  $add_php_close_key = 'echo "?>" >> $1';
  $add_last_space = 'sed -z "s/.$//" -i $1';

  $cmd = <<<CMD
  #!/bin/bash

  unblockSqlModuleQuery() {
      if [ -f \$1 ]
      then
          $remove_php_open_key_tmp
          $remove_php_open_multiline_comment_tmp
          $remove_php_close_multiline_comment_tmp
          $remove_php_close_key_tmp
          $remove_first_space_tmp
          $remove_second_space_tmp
          $remove_last_space_tmp
      fi
  }

  runModuleOnServe() {
      if [ -f \$1 ]
      then
          mysql -uroot -p1234 $db < \$1
      fi
  }

  blockSqlModuleQuery() {
      if [ -f \$1 ]
      then
          $add_php_multiline_comment
          $add_php_open_key_comment
          $add_php_close_multiline_comment
          $add_php_close_key
          $add_last_space
      fi
  }

  runSteps() {
      unblockSqlModuleQuery \$1
      runModuleOnServe \$1 || true
      blockSqlModuleQuery \$1
  }

  scaleModules() {
      for moduleSql in module/*/*.sql.php; do runSteps \$moduleSql; done
  }

  scaleModules 2>&1
  CMD;

  if ($enable) {
    echo '<h3>Database information: </h3>';
    echo '<br>';
    echo exec($cmd);
  }

}

//user identification
function identify($conn, $table, $params) {
  $sql =  '';
  //create query
  $sql .= 'SELECT ';
  $sql .= 'name, ';
  $sql .= 'password, ';
  $sql .= 'softDelete ';
  $sql .= "FROM $table ";
  $sql .= 'WHERE name = ? ';

  //prepare statement
  $stmt = $conn->prepare($sql);
  //binding param
  $stmt->bindParam(1, $params['identify']);
  //execute query
  if ($stmt->execute()) {

    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row['softDelete']) {
      return false;
    }

    if (password_verify($params['hash'], $row['password'])) {
      return true;
    }
  }

  //print error if something goes wrong
  printf("Error smtm %s. \n", $stmt->error);
  return false;
}

?>